package com.wxh.lock;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName: RWSample
 * @Description: 读写样例:基于读写锁实现数据结构
 * @Author wxh
 * @Date: 2022/2/9 15:52
 * @Version V1.0.0
 * @Since 1.8
 */
public class RWSample {
    private final Map<String, String> map = new TreeMap<>();
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock read = rwLock.readLock();
    private final Lock write = rwLock.writeLock();

    public String get(String key){
        System.out.println("读锁锁定！");
        read.lock();
        try {
            return map.get(key);
        }finally {
            read.unlock();
        }
    }

    public String put(String key, String value){
        System.out.println("写锁锁定！");
        write.lock();
        try {
            return map.put(key, value);
        }finally {
            write.unlock();
        }
    }
}
